/*
 * =====================================================================================
 *
 *       Filename:  ResponsibilityChain.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015年02月28日 18时10分48秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  LiuYi (), swliuyi@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <limits.h>
#include <iostream>

using namespace std;

class Handler
{
    protected:
        Handler * m_successor;
    public:
        Handler():m_successor(NULL) { }
        void SetSuccessor(Handler * successor)
        {
            m_successor = successor;
        }
        virtual void HandleRequest(int request) = 0;
        virtual ~Handler()
        {
            delete m_successor;
        }
};

class ConcreteHandler1 : public Handler
{
    public:
        void HandleRequest(int request)
        {
            if( request >= 0 && request < 10 )
            {
                cout<<"ConcreteHandler1 handle request:"<<request<<endl;
            }
            else if( m_successor != NULL )
            {
                m_successor->HandleRequest(request);
            }
        }
};

class ConcreteHandler2 : public Handler
{
    public:
        void HandleRequest(int request)
        {
            if( request >= 10 && request < 20 )
            {
                cout<<"ConcreteHandler2 handle request:"<<request<<endl;
            }
            else if( m_successor != NULL )
            {
                m_successor->HandleRequest(request);
            }
        }
};

class ConcreteHandler3 : public Handler
{
    public:
        void HandleRequest(int request)
        {
            if( request >= 20 && request < 30 )
            {
                cout<<"ConcreteHandler3 handle request:"<<request<<endl;
            }
            else if( m_successor != NULL )
            {
                m_successor->HandleRequest(request);
            }
        }
};

int main(int argc, char *argv[])
{
    Handler * h1 = new ConcreteHandler1();
    Handler * h2 = new ConcreteHandler2();
    Handler * h3 = new ConcreteHandler3();
    h1->SetSuccessor(h2);
    h2->SetSuccessor(h3);

    int arr[7] = {2, 5, 14, 22, 18, 3, 17};

    for( int i = 0 ; i < 7 ; i++ )
    {
        h1->HandleRequest(arr[i]);
    }
    
    delete h1;
}
